package com.leyou.upload.service;


import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.OSSConfig;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class UploadService {

    private static final String UPLOAD_DIR = "D:\\Nginx\\nginx-1.12.2\\html";

    private static final String IMAGE_HOST = "http://image.leyou.com/";

    private static final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/png", "image/jpeg", "image/bmp");

    public String upload(MultipartFile file) {
        //1.文件的校验
        //1.1检验文件类型
        String contentType = file.getContentType();
        if (!ALLOW_CONTENT_TYPES.contains(contentType)) {
            //文件有误
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //1.2校验文件内容
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            log.error("文件上传有误！", e);
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE, e);
        }

        //获取文件名称
        String filename = file.getOriginalFilename();
        //准备目标文件的地址
        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File dest = new File(dir, filename);
        //保存文件
        try {
            file.transferTo(dest);
            return IMAGE_HOST + filename;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    public Map<String, Object> getSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}